package org.jairou.util;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jairou.core.Objects;
import org.jairou.core.XML;

public class Upload {
	
	public static void write(String name, Object item) 
	throws Exception {		
		String path = ".";
		if (XML.contains("file-upload.path")) {
			path = XML.get("file-upload.path");
		}
		File file = new File(path+"/"+name);		
		((FileItem)item).write(file);
	}
	
	public static boolean isMultipart(HttpServletRequest req) {
		return ServletFileUpload.isMultipartContent(req);            	 
	}
	
	public static void addItems(Object ctx) 
	throws Exception {
		HttpServletRequest req = (HttpServletRequest) Objects.get("request", ctx);
		
		DiskFileItemFactory factory = new DiskFileItemFactory();		
		ServletFileUpload upload;
        
		if (XML.contains("file-upload.tempDirectory") && 
			XML.contains("file-upload.sizeThreshold") && 
			XML.contains("file-upload.requestSize") ) {
			
			int sizeThreshold = Integer.parseInt(XML.get("file-upload.sizeThreshold"));
        	int requestSize = Integer.parseInt(XML.get("file-upload.requestSize"));
        	String tempDirectory = XML.get("file-upload.tempDirectory");
        	
        	// Set factory constraints
        	factory.setSizeThreshold(sizeThreshold);
        	factory.setRepository(new java.io.File(tempDirectory));
                	
            upload = new ServletFileUpload(factory);
            // Set overall request size constraint
            upload.setSizeMax(requestSize);
		}
		else upload = new ServletFileUpload(factory);	
    	
        List<FileItem> items = upload.parseRequest(req);    
        for (FileItem item : items) {
            if (!item.isFormField()) {
                Objects.set(item.getFieldName(), item, ctx);
            }
            else Objects.set(item.getFieldName(), item.getString(), ctx);
        }
    }   
}